<template>
  <view class="page-container" :class="themeClass">
    <!-- 自定义导航栏 -->
    <CustomNavBar 
      :title="isEdit ? '编辑日记' : '写日记'" 
      :show-back="isEdit"
      @back="handleBack"
      @rightClick="handleSave"
    >
      <template #right>
        <text class="save-btn" :class="{ disabled: !canSave }">{{ saving ? '保存中' : '保存' }}</text>
      </template>
    </CustomNavBar>
    
    <!-- 页面内容 -->
    <view class="page-content" :style="{ paddingTop: navBarHeight + 'px' }">
      <scroll-view scroll-y class="content-scroll">
        <!-- 标题输入 -->
        <view class="title-section">
          <input
            v-model="formData.title"
            placeholder="请输入日记标题..."
            class="title-input"
            :focus="titleFocus"
            @blur="titleFocus = false"
          />
        </view>
        
        <!-- 工具栏 -->
        <view class="toolbar">
          <view class="toolbar-left">
            <view class="tool-item disabled">
              <text class="tool-icon">📅</text>
              <text class="tool-text">{{ formatDate(formData.diaryDate) }}</text>
            </view>
            
            <view class="tool-item" @click="selectWeather">
              <text class="tool-icon">🌤️</text>
              <text class="tool-text">{{ formData.weather || '天气' }}</text>
            </view>
            
            <view class="tool-item" @click="selectMood">
              <text class="mood-emoji">{{ getMoodEmoji(formData.mood) }}</text>
              <text class="tool-text">{{ formData.mood || '心情' }}</text>
            </view>
          </view>
          

        </view>
        
        <!-- 图文混编编辑器 -->
        <view class="editor-section">
          <RichTextEditor 
            v-model:value="formData.content"
            :placeholder="editorPlaceholder"
            :theme-mode="userStore.themeMode"
            @focus="onEditorFocus"
            @blur="onEditorBlur"
          />
        </view>
        
        <!-- 分类和标签 -->
        <view class="meta-section">
          <view class="meta-row">
            <text class="meta-label">分类</text>
            <view class="meta-content" @click="selectCategory">
              <text class="meta-value" :class="{ placeholder: !formData.categoryId }">
                {{ selectedCategoryName || '选择分类' }}
              </text>
              <uni-icons type="right" size="16" color="#ccc"></uni-icons>
            </view>
          </view>
          
          <view class="meta-row">
            <text class="meta-label">标签</text>
            <view class="meta-content" @click="selectTags">
              <text class="meta-value" :class="{ placeholder: !formData.tagIds.length }">
                {{ selectedTagsText || '添加标签' }}
              </text>
              <uni-icons type="right" size="16" color="#ccc"></uni-icons>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 日期选择器已禁用，日记只能写当天 -->
    
    <!-- 天气选择弹窗 -->
    <WeatherModal 
      v-model:show="showWeatherModal"
      :selected="formData.weather"
      @select="onWeatherSelect"
    />
    
    <!-- 心情选择弹窗 -->
    <MoodModal 
      v-model:show="showMoodModal"
      :selected="formData.mood"
      @select="onMoodSelect"
    />
    
    <!-- 分类选择弹窗 -->
    <CategoryModal 
      v-model:show="showCategoryModal"
      :categories="categories"
      :selected="formData.categoryId"
      @select="onCategorySelect"
      @create="createCategory"
    />
    
    <!-- 标签选择弹窗 -->
    <TagModal 
      v-model:show="showTagModal"
      :tags="tags"
      :selected="formData.tagIds"
      @confirm="onTagsConfirm"
      @create="createTag"
    />
    
    <!-- 加载组件 -->
    <LoadingComponent :visible="loading || saving" :text="saving ? '保存中...' : '加载中...'" />
  </view>
</template>

<script>
import { useDiaryStore } from '@/store/diary'
import { useUserStore } from '@/store/user'
import { 
  getDiaryDetailAPI, 
  createDiaryAPI, 
  updateDiaryAPI 
} from '@/api/diary'
import { getCategoriesAPI, createCategoryAPI } from '@/api/category'
import { getTagsAPI, createTagAPI } from '@/api/tag'
import { upload } from '@/utils/request'
import { formatDate, extractResponseData } from '@/utils/index'
import CustomNavBar from '@/components/CustomNavBar.vue'
import LoadingComponent from '@/components/LoadingComponent.vue'
import WeatherModal from '@/components/WeatherModal.vue'
import MoodModal from '@/components/MoodModal.vue'
import CategoryModal from '@/components/CategoryModal.vue' 
import TagModal from '@/components/TagModal.vue'
import RichTextEditor from '@/components/RichTextEditor.vue'

export default {
  name: 'DiaryEditPage',
  components: {
    CustomNavBar,
    LoadingComponent,
    WeatherModal,
    MoodModal,
    CategoryModal,
    TagModal,
    RichTextEditor
  },
  setup() {
    const diaryStore = useDiaryStore()
    const userStore = useUserStore()
    
    return {
      diaryStore,
      userStore,
      formatDate
    }
  },
  data() {
    return {
      navBarHeight: 88,
      diaryId: null,
      isEdit: false,
      loading: false,
      saving: false,
      titleFocus: false,
      contentFocus: false,
      
      formData: {
        title: '',
        content: '',
        diaryDate: '',
        categoryId: null,
        tagIds: [],
        weather: '',
        mood: ''
      },
      
      categories: [],
      tags: [],
      
      // 弹窗状态
      showWeatherModal: false,
      showMoodModal: false,
      showCategoryModal: false,
      showTagModal: false,
      
      // 日期范围
      minDate: '2020-01-01',
      maxDate: '',
      
      // 天气选项
      weatherOptions: ['晴天', '多云', '阴天', '小雨', '大雨', '雪天', '雾天'],
      
      // 心情选项
      moodOptions: [
        { name: '开心', emoji: '😊' },
        { name: '平静', emoji: '😌' },
        { name: '兴奋', emoji: '🤩' },
        { name: '难过', emoji: '😢' },
        { name: '愤怒', emoji: '😠' },
        { name: '焦虑', emoji: '😰' },
        { name: '疲惫', emoji: '😴' },
        { name: '感动', emoji: '🥺' }
      ],
      
      editorPlaceholder: '记录你的美好时光...'
    }
  },
  computed: {
    themeClass() {
      return this.userStore.themeMode === 'dark' ? 'theme-dark' : 'theme-light'
    },
    
    canSave() {
      return this.formData.title.trim() && !this.saving
    },
    
    selectedCategoryName() {
      if (!this.formData.categoryId) return ''
      const category = this.categories.find(c => c.id === this.formData.categoryId)
      return category ? category.name : ''
    },
    
    selectedTagsText() {
      if (!this.formData.tagIds.length) return ''
      const selectedTags = this.tags.filter(t => this.formData.tagIds.includes(t.id))
      return selectedTags.map(t => t.name).join(', ')
    }
  },
  onLoad(options) {
    // 从状态管理中获取编辑信息
    this.diaryId = this.diaryStore.editingDiaryId
    this.isEdit = !!this.diaryId
    
    // 如果有传入的日期参数，也设置一下
    if (options.date) {
      this.diaryStore.setEditingDiary(null, options.date)
    }
    
    this.initPage()
  },
  onShow() {
    // 如果不是通过编辑跳转过来，且当前是编辑模式，则清除编辑状态
    if (!this.diaryStore.editingDiaryId && this.isEdit) {
      this.isEdit = false
      this.diaryId = null
      this.initPage()
    }
    
    // 重新加载分类和标签数据（用户可能在其他页面创建了新的分类或标签）
    this.loadBasicData()
    
    this.contentFocus = true
  },
  methods: {
    async initPage() {
      // 检查登录状态
      if (!this.userStore.checkLoginStatus()) return
      
      // 获取导航栏高度
      const systemInfo = uni.getSystemInfoSync()
      this.navBarHeight = systemInfo.statusBarHeight + 44
      
      // 设置日期范围
      this.maxDate = formatDate(new Date())
      
      // 初始化表单数据
      if (!this.isEdit) {
        // 如果有预设的日期，使用预设日期，否则使用当前日期
        const defaultDate = this.diaryStore.editingDate || formatDate(new Date())
        this.formData.diaryDate = defaultDate
        this.titleFocus = true
      }
      
      // 加载基础数据
      await this.loadBasicData()
      
      // 如果是编辑模式，加载日记详情
      if (this.isEdit) {
        await this.loadDiaryDetail()
      }
    },
    
    async loadBasicData() {
      try {
        const [categoriesRes, tagsRes] = await Promise.all([
          getCategoriesAPI(),
          getTagsAPI()
        ])
        
        const categoriesData = extractResponseData(categoriesRes)
        const tagsData = extractResponseData(tagsRes)
        
        this.categories = categoriesData || []
        this.tags = tagsData || []
      } catch (error) {
        console.error('加载基础数据失败:', error)
      }
    },
    
    async loadDiaryDetail() {
      if (!this.diaryId) return
      
      this.loading = true
      
      try {
        const res = await getDiaryDetailAPI(this.diaryId)
        const diary = extractResponseData(res)
        
        this.formData = {
          title: diary.title || '',
          content: diary.content || '',
          diaryDate: diary.diaryDate || '',
          categoryId: diary.category?.id || null,
          tagIds: diary.tags?.map(t => t.id) || [],
          weather: diary.weather || '',
          mood: diary.mood || ''
        }
        
        // 设置编辑器内容
        this.setEditorContent()
        
      } catch (error) {
        console.error('加载日记详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } finally {
        this.loading = false
      }
    },
    
    // 处理返回
    async handleBack() {
      if (this.hasUnsavedChanges()) {
        try {
          await uni.showModal({
            title: '提示',
            content: '有未保存的内容，确定要离开吗？',
            showCancel: true
          })
          // 清除编辑状态
          this.diaryStore.clearEditingState()
          uni.navigateBack()
        } catch (error) {
          // 用户取消
        }
      } else {
        // 清除编辑状态
        this.diaryStore.clearEditingState()
        uni.navigateBack()
      }
    },
    
    // 检查是否有未保存的更改
    hasUnsavedChanges() {
      // 这里可以实现更复杂的检查逻辑
      return this.formData.title.trim() || this.formData.content.trim()
    },
    
    // 处理保存
    async handleSave() {
      if (!this.canSave) return
      
      this.saving = true
      
      try {
        // 获取富文本编辑器内容
        const content = await this.getEditorContent()
        
        const data = {
          title: this.formData.title.trim(),
          content: content,
          diaryDate: this.formData.diaryDate,
          categoryId: this.formData.categoryId,
          tagIds: this.formData.tagIds,
          weather: this.formData.weather,
          mood: this.formData.mood
        }
        
        let res
        if (this.isEdit) {
          res = await updateDiaryAPI(this.diaryId, data)
        } else {
          res = await createDiaryAPI(data)
        }
        
        const savedDiary = extractResponseData(res)
        
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        // 更新状态管理
        this.diaryStore.addOrUpdateDiary(savedDiary)
        
        // 清除编辑状态
        this.diaryStore.clearEditingState()
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        console.error('保存失败:', error)
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      } finally {
        this.saving = false
      }
    },
    
    // 日期选择已禁用，日记只能写当天
    
    // 天气选择
    selectWeather() {
      this.showWeatherModal = true
    },
    
    onWeatherSelect(weather) {
      this.formData.weather = weather
      this.showWeatherModal = false
    },
    
    // 心情选择
    selectMood() {
      this.showMoodModal = true
    },
    
    onMoodSelect(mood) {
      this.formData.mood = mood
      this.showMoodModal = false
    },
    
    getMoodEmoji(mood) {
      const moodOption = this.moodOptions.find(m => m.name === mood)
      return moodOption ? moodOption.emoji : '😊'
    },
    

    
    // 分类选择
    selectCategory() {
      this.showCategoryModal = true
    },
    
    onCategorySelect(categoryId) {
      this.formData.categoryId = categoryId
      this.showCategoryModal = false
    },
    
    createCategory() {
      // 关闭弹窗
      this.showCategoryModal = false
      
      // 跳转到分类编辑页面
      uni.navigateTo({
        url: '/pages/category/edit'
      })
    },
    
    // 标签选择
    selectTags() {
      this.showTagModal = true
    },
    
    onTagsConfirm(tagIds) {
      this.formData.tagIds = tagIds
      this.showTagModal = false
    },
    
    createTag() {
      // 关闭弹窗
      this.showTagModal = false
      
      // 跳转到标签编辑页面
      uni.navigateTo({
        url: '/pages/tag/edit'
      })
    },
    
    // 编辑器事件处理
    
    onEditorFocus() {
      this.contentFocus = true
    },
    
    onEditorBlur() {
      this.contentFocus = false
    },
    
    // 内容自动通过v-model双向绑定，无需手动处理
  }
}
</script>

<style scoped>
.content-scroll {
  height: calc(100vh - 88px);
  padding-bottom: 120rpx;
}

.title-section {
  padding: 40rpx 32rpx 20rpx;
}

.title-input {
  width: 100%;
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
  border: none;
  background-color: transparent;
}

.title-input::placeholder {
  color: #cccccc;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 32rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.toolbar-left {
  display: flex;
  gap: 32rpx;
}

.toolbar-right {
  display: flex;
  gap: 32rpx;
}

.tool-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 16rpx;
  border-radius: 20rpx;
  background-color: #f8f8f8;
}

.tool-item.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.tool-text {
  font-size: 24rpx;
  color: #666666;
}

.mood-emoji {
  font-size: 20rpx;
}

.images-section {
  padding: 20rpx 32rpx;
}

.images-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.image-wrapper {
  position: relative;
  width: 200rpx;
  height: 200rpx;
}

.image-item {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
  background-color: #f0f0f0;
}

.image-delete {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  width: 32rpx;
  height: 32rpx;
  border-radius: 16rpx;
  background-color: #ff4d4f;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-image {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #cccccc;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.editor-section {
  padding: 20rpx 32rpx;
}

.content-editor {
  width: 100%;
  min-height: 400rpx;
  font-size: 30rpx;
  line-height: 1.6;
  color: #333333;
  background-color: transparent;
  border: none;
}

.content-editor::placeholder {
  color: #cccccc;
}

.meta-section {
  padding: 0 32rpx 40rpx;
}

.meta-row {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.meta-row:last-child {
  border-bottom: none;
}

.meta-label {
  width: 120rpx;
  font-size: 28rpx;
  color: #333333;
}

.meta-content {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.meta-value {
  font-size: 28rpx;
  color: #333333;
}

.meta-value.placeholder {
  color: #cccccc;
}

.save-btn {
  font-size: 28rpx;
  color: #1890ff;
}

.save-btn.disabled {
  color: #cccccc;
}

/* 编辑器样式已移至RichTextEditor组件中 */

/* 主题适配 */
.theme-light.page-container {
  background-color: #f5f5f5 !important;
}

.theme-dark.page-container {
  background-color: #1e1e1e !important;
}

.theme-dark .title-input {
  color: #e8e8e8;
}

.theme-dark .title-input::placeholder {
  color: #8c8c8c;
}

.theme-dark .toolbar {
  border-bottom-color: #404040;
}

.theme-dark .tool-item {
  background-color: #404040;
}

.theme-dark .tool-text {
  color: #b3b3b3;
}

.theme-dark .tool-item.disabled {
  opacity: 0.4;
}

/* 深色主题样式已移至RichTextEditor组件中 */

.theme-dark .content-textarea::placeholder {
  color: #8c8c8c;
}

.theme-dark .meta-row {
  border-bottom-color: #404040;
}

.theme-dark .meta-label,
.theme-dark .meta-value {
  color: #e8e8e8;
}

.theme-dark .meta-value.placeholder {
  color: #8c8c8c;
}
</style> 